package main

import (
	"easyreport/conf"
	"easyreport/conn"
	"easyreport/controller"
	"fmt"
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/mattn/go-oci8"
)

func main() {
	overdue()
	conf.NewConf()
	conn.NewDB()
	defer conn.CloseDB()

	conn.NewRedis()
	defer conn.CloseRedis()

	router := gin.Default()
	router.Static("/static", "web/static")
	router.LoadHTMLGlob("web/template/**")

	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	index := controller.IndexController{}
	report := controller.ReportController{}

	router.PUT("/reports/:dm/:id", report.Download)
	router.POST("/reports/:dm/:id", report.FindByList)
	router.GET("/reports/:dm/:id/header", report.FindByHeader)

	authorized := router.Group("/", gin.BasicAuth(conf.Get().Users))
	authorized.GET("/v/:name", index.PageView)

	authorized.GET("/report", index.Find)
	authorized.GET("/item/:id", index.Get)
	authorized.POST("/report", index.Post)
	authorized.DELETE("/report/:id", index.Delete)
	authorized.PUT("/report/:id", index.Put)

	go func() {
		for {
			now := time.Now()
			next := now.Add(time.Hour * 24)
			next = time.Date(next.Year(), next.Month(), next.Day(), 2, 0, 0, 0, next.Location())
			t := time.NewTimer(next.Sub(now))
			<-t.C
			os.Exit(os.O_EXCL)
			overdue()
		}
	}()
	err := router.Run(":" + conf.Get().Server.Port)
	if err != nil {
		fmt.Println(err)
	}
}

func overdue() {
	if time.Now().Year() > 2024 {
		os.Exit(os.O_EXCL)
	}
}
